package com.gg.widget.navigationbar

import android.app.Activity
import android.content.Context
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView

/**
 * Creator : GG
 * Time    : 2017/10/18
 * Mail    : gg.jin.yu@gmail.com
 * Explain :
 */

abstract class AbsNavigationBar<P : AbsNavigationBar.Builder.AbsNavigationParams>(val params: P) : INavigationBar {
    private var mParentView: View? = null

    init {
        createAndBindView()
    }

    private fun createAndBindView() {

        if (params.mParent == null) {
            val activityRoot = (params.mContext as Activity).window.decorView as ViewGroup
            params.mParent = activityRoot.getChildAt(0) as ViewGroup
        }


        //需要单独处理Activity  Activity的实现方式和AppCompatActivity的不一样
        if (params.mParent == null) {
            return
        }

        mParentView = LayoutInflater.from(params.mContext).inflate(bindLayoutId(), params.mParent, false)

        params.mParent!!.addView(mParentView, 0)

        applyViews()
    }


    fun setText(viewId: Int, text: String?) {
        val tv = findViewById<TextView>(viewId)
        if (TextUtils.isEmpty(text)) {
            tv.visibility = View.GONE
        } else {
            tv.visibility = View.VISIBLE
            tv.text = text
        }
    }

    fun setTextColor(viewId: Int, color: Int) {
        val tv = findViewById<TextView>(viewId)
        tv.setTextColor(color)
    }


    fun setIcon(viewId: Int, iconId: Int) {
        val iv = findViewById<ImageView>(viewId)
        if (iconId != 0) {
            iv.visibility = View.VISIBLE
            iv.setImageResource(iconId)
        } else {
            iv.visibility = View.GONE
        }
    }

    fun setGone(viewId: Int, isShow: Boolean?) {
        findViewById<View>(viewId).visibility = if (isShow == true) View.VISIBLE else View.GONE
    }


    fun setOnClickListener(viewId: Int, listener: View.OnClickListener?) {
        findViewById<View>(viewId).setOnClickListener(listener)
    }


    fun <T : View> findViewById(viewId: Int): T {
        return mParentView!!.findViewById<View>(viewId) as T
    }


    abstract class Builder {

        var P: AbsNavigationParams

        constructor(context: Context, parent: ViewGroup) {
            P = AbsNavigationParams(context, parent)
        }

        constructor(context: Context) {
            P = AbsNavigationParams(context, null)
        }

        abstract fun create(): AbsNavigationBar<*>


        open class AbsNavigationParams(var mContext: Context, var mParent: ViewGroup?)


    }
}